﻿using System;
using System.Web.UI.WebControls;
using Entity;
using BLL.Access;
using System.Data;
using Web.Class;
using BLL;
using DevExpress.Web;
using System.IO;

namespace Web.Pages.YongShui._13.LAIHANGL
{
    public partial class LAIHANWJLB : BasePage
    {
        #region 属性
       

        #endregion

        #region 变量
       
        /// <summary>
        /// 上传
        /// </summary>
        SYS_UPLOADProcess uploadBLL = new SYS_UPLOADProcess();

        SYS_UPLOAD_LOGBLL uploadLOGBLL = new SYS_UPLOAD_LOGBLL();
        /// <summary>
        /// 来函信息BLL
        /// </summary>
        YS_LH_LAIHANXXProcess BllLaiHanXX = new YS_LH_LAIHANXXProcess();
        /// <summary>
        ///     访问数据库
        /// </summary>
        private readonly SpHelper _sphelper = new SpHelper();
        private string needFileBH;
        #endregion

        #region 事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //20190327 添加特殊权限点可修改功能
                if (Request["lhflag"] != null && Convert.ToInt32(Request["lhflag"]) >= 1)
                {
                    divUpload.Visible = true;
                    InitControl();
                }
                else
                {
                    divUpload.Visible = false;
                }
                BindUploadGV();
            }
            needFileBH = LaiHanLCTools.GetNeedFileBH(Convert.ToInt32(Request["laihanlx"]));
        }

        /// <summary>
        /// 后台回调
        /// </summary>
        protected void ASPxCallback1_Callback(object source, CallbackEventArgs e)
        {
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        protected void UpLoadFile_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            e.CallbackData = SavePostedFile(e.UploadedFile);
        }

        /// <summary>
        /// 客户端刷新list
        /// </summary>
        protected void gvWenJian_CustomCallback(object sender, DevExpress.Web.ASPxGridViewCustomCallbackEventArgs e)
        {
            BindUploadGV(); 
        }

        #endregion

        #region 方法
        /// <summary>
        /// 修改时加载数据
        /// </summary>
        private void InitControl()
        {
            hdCollection.Set("wtype", BusinessTool.WType);
            hdCollection.Set("laihanlx", Convert.ToInt32(Request["laihanlx"]));
            hdCollection.Set("laihanbh", Request["laihanbh"]);
            hdCollection.Set("yonghuh", Request["yonghuh"]);

            var ds = _sphelper.P_YS_LH_LAIHANZLLB(Convert.ToInt32(Request["laihanlx"]));
            cmbCaiLiaoLB.DataSource = ds.Tables[0];
            cmbCaiLiaoLB.TextField = "S_CAILIAOMC";
            cmbCaiLiaoLB.ValueField = "I_CAILIAOBH";
            cmbCaiLiaoLB.DataBind();
            cmbCaiLiaoLB.SelectedIndex = 0;
            if (ds.Tables[0].Rows.Count > 0)
            {
                hdCollection.Set("cllb", ds.Tables[0].Rows[0]["I_CAILIAOBH"]);
                hdCollection.Set("cllbmc", ds.Tables[0].Rows[0]["S_CAILIAOMC"]);
            }

            Session["gaopai"] = null;
        }

        /// <summary>
        /// 保存上传文件
        /// </summary>
        private string SavePostedFile(UploadedFile uploadedFile)
        {
            var uploadDirectory = PageTools.GetUploadPath(BusinessTool.WType, "lh");
            if (!uploadedFile.IsValid) return string.Empty;
            var fileName = Guid.NewGuid() + Path.GetExtension(uploadedFile.FileName); //文件名
            var filePath = Path.Combine(Server.MapPath(uploadDirectory), fileName); //文件完整物理路径
            uploadedFile.SaveAs(filePath);

            int cllb = 0;
            string lbmc = "";
            if (hdCollection.Contains("cllb"))
                cllb = Convert.ToInt32(hdCollection.Get("cllb"));
            if (hdCollection.Contains("cllbmc"))
                lbmc = hdCollection.Get("cllbmc").ToString();
            //文件上传记录存入数据库
            var uploadlog = new SYS_UPLOAD_LOG();
            uploadlog.D_CAOZUORQ = DateTime.Now;
            uploadlog.I_CAOZUOR = LoginInfo.CurrentUser.UserID;
            uploadlog.I_JLZT = 0;
            uploadlog.I_TYPE = BusinessTool.WType;
            uploadlog.I_WENJIANLX = cllb;
            uploadlog.ID = 0;
            uploadlog.S_WENJIANLJ = Path.Combine(uploadDirectory, fileName);
            uploadlog.S_WENJIANMC = lbmc;
            uploadlog.S_YONGHUBH = Request["yonghuh"];
            uploadLOGBLL.InsertOrUpdate(uploadlog);
            //上传内容
            var upload = new SYS_UPLOAD();
            upload.I_JLZT = 0;
            upload.D_CAOZUORQ = uploadlog.D_CAOZUORQ;
            upload.S_CAOZUOR = uploadlog.I_CAOZUOR.ToString();
            upload.I_TYPE = BusinessTool.WType;
            upload.I_WENJIANLX = uploadlog.I_WENJIANLX;
            //如果为申请表,同一用户同一类型尚未有来函编号的 最多只存在一个
            needFileBH = LaiHanLCTools.GetNeedFileBH(Convert.ToInt32(Request["laihanlx"]));
            var where = "";
            int index = Array.IndexOf(needFileBH.Split(','), upload.I_WENJIANLX.ToString());
            if (index >= 0)
            {
                where = "I_JLZT=0 AND S_YONGHUBH='" + Request["yonghuh"] + "' AND I_WENJIANLX=" + upload.I_WENJIANLX +
                        (!string.IsNullOrEmpty(Request["laihanbh"])
                            ? " AND S_LAIHANBH='" + Request["laihanbh"] + "'"
                            : " AND S_LAIHANBH IS NULL");
                upload.S_LAIHANBH = Request["laihanbh"];
            }
            else
            {
                where = "I_JLZT=0 AND S_YONGHUBH='" + Request["yonghuh"] + "' AND I_WENJIANLX=" + upload.I_WENJIANLX + " AND S_LAIHANBH IS NULL";
            }

            var shangchuan = uploadBLL.SelectSYS_UPLOADsDynamic(where, "", null);
            if (shangchuan != null && shangchuan.Rows.Count > 0) upload.ID = Convert.ToInt32(shangchuan.Rows[0]["ID"]);
            upload.S_WENJIANLJ = uploadlog.S_WENJIANLJ;
            upload.S_WENJIANMC = uploadlog.S_WENJIANMC;
            upload.S_YONGHUBH = uploadlog.S_YONGHUBH;
            if (string.IsNullOrEmpty(upload.S_LAIHANBH))
                upload.S_LAIHANBH = Request["laihanbh"];
            upload.I_SHANGCHUANLB = 1; //普通上传
            upload.I_SUOSHUMK = 1; //来函
            uploadBLL.InsertOrUpdate(upload);

            return filePath; //返回文件名用于预览
        }
        private void BindUploadGV()
        {
            string yhh=Request["yonghuh"];
            string lhbh = string.IsNullOrEmpty(Request["laihanbh"]) || Request["laihanbh"] == "undefined"||Request["laihanbh"] == "null" ? null : Request["laihanbh"];
            if (string.IsNullOrEmpty(yhh))
            {
                PageTools.AlertMsg(this, "请先选择用户信息");
                return;
            }
            string needFileBH = LaiHanLCTools.GetNeedFileBH(Convert.ToInt32(Request["laihanlx"]));
            string where = LaiHanLCTools.GetUserFilesCondition(yhh,lhbh,needFileBH);
            /*
            if (string.IsNullOrEmpty(lhbh)||lhbh.ToLower()=="null")
            {
                where = "I_JLZT=0 AND S_YONGHUBH='" + yhh + "' AND S_LAIHANBH IS NULL";
            }
            else
            {
                where = "I_JLZT=0 AND S_YONGHUBH='" + yhh + "' AND (S_LAIHANBH IS NULL OR S_LAIHANBH='" + lhbh + "')";
            }
            */
                //where = string.Format("I_JLZT=0 and ((S_YONGHUBH='{0}' and I_WENJIANLX<>{1}) or (S_LAIHANBH='{2}'))", Request["yonghuh"], needFileBH, Request["laihanbh"]);
            //where = string.Format("I_JLZT=0 and (S_YONGHUBH='{0}' OR (I_WENJIANLX="+needFileBH+" AND " + (string.IsNullOrEmpty(lhbh) ? "S_LAIHANBH IS NULL" : "S_LAIHANBH='{1}'))"), yhh, lhbh);
                //where = "I_JLZT=0 and ((S_YONGHUBH='{0}' and I_WENJIANLX<>" + needFileBH+")";
                //if (!string.IsNullOrEmpty(Request["laihanbh"]))
                //{
                //    where = where + " or (S_LAIHANBH=" + Request["laihanbh"] + "))";
                //}
                //where = string.Format(" (S_YONGHUBH='{0}' and I_WENJIANLX<>" + needFileBH + ") and I_JLZT=0 ", Request["yonghuh"]);
         
            //string leixingcailiao = "";
            //if (needFileBH != "0")
            //{
            //    leixingcailiao = " and I_WENJIANLX in (select a.i_cailiaolbbh from ys_lh_laihanlxcl a where a.i_laihanlx=" + Request["laihanlx"] + ") ";
            //}
            //if (!string.IsNullOrEmpty(Request["laihanbh"]))
            //{
            //    //where = string.Format(" (S_YONGHUBH='{1}' and (S_LAIHANBH='{0}' or I_WENJIANLX<>" + needFileBH + " ) ) and i_jlzt=0 ", Request["laihanbh"], Request["yonghuh"]);
            //    where = string.Format(" (S_LAIHANBH='{0}' and i_jlzt=0 )", Request["laihanbh"]);
            //}

            //DataTable dt = bllupload.SelectSYS_UPLOADsDynamic(where + leixingcailiao, "", null);
            DataTable dt = uploadBLL.SelectSYS_UPLOADsDynamic(where,null);

            gvWenJian.DataSource = ChangeDt(dt); 
            gvWenJian.DataBind();
            SetVisabled();
        }
        private DataTable ChangeDt(DataTable dt)
        {
            DataTable newdt = dt.Clone();
            newdt.Columns["ID"].DataType = newdt.Columns["S_WENJIANLJ"].DataType;
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    DataRow newdr = newdt.NewRow();
                    newdr["S_WENJIANMC"] = dr["S_WENJIANMC"];
                    newdr["S_WENJIANLJ"] = imageHandler(dr["S_WENJIANLJ"].ToString());
                    newdr["ID"] = dr["ID"];
                    newdt.Rows.Add(newdr);
                }
            }
            if (Session["gaopai"] != null)
            {
                DataTable cailiao = Session["gaopai"] as DataTable;
                if (cailiao != null && cailiao.Rows.Count > 0)
                {
                    foreach (DataRow dr in cailiao.Rows)
                    {
                        DataRow newdr = newdt.NewRow();
                        newdr["S_WENJIANMC"] = dr["name"];
                        newdr["S_WENJIANLJ"] = dr["path"].ToString();
                        newdr["ID"] = dr["name"] + dr["path"].ToString();
                        newdt.Rows.Add(newdr);
                    }
                }
            }
            return newdt;
        }
        private string imageHandler(string path)
        {
            var host = Request.Url.ToString().Replace("http://", "").Split('/')[0];
            path = "http://" + host + "/" + path;
            var filePath = path.ToString().ToLower();
            if (filePath.EndsWith("jpg") || filePath.EndsWith("png") || filePath.EndsWith("jpeg") ||
                filePath.EndsWith("bmp"))
            {
                path = "http://" + host + "/ImageView.html?img=" + path;
            }
            return path;
        }
        private void DeleteSession(string id)
        {
            if (Session["gaopai"] != null)
            {
                DataTable cailiao = Session["gaopai"] as DataTable;
                DataTable newdt = cailiao.Clone();
                
                if (cailiao != null && cailiao.Rows.Count > 0)
                {
                    foreach (DataRow dr in cailiao.Rows)
                    {
                        if (dr["name"].ToString() + dr["path"].ToString() != id)
                        {
                            DataRow newdr = newdt.NewRow();
                            foreach (DataColumn d in cailiao.Columns)
                            { 
                                newdr[d.ColumnName]=dr[d.ColumnName];
                            }
                            newdt.Rows.Add(newdr);
                        }
                    }
                }
                Session["gaopai"] = newdt;
            }
        }
        
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnbDel_Command(object sender, CommandEventArgs e)
        {
            int sid = -1;
            if (!int.TryParse(e.CommandArgument.ToString(), out sid))
            {
                DeleteSession(e.CommandArgument.ToString());
                BindUploadGV();
                return;
            }
            int id = Convert.ToInt32(e.CommandArgument);
            
            SYS_UPLOAD uploadinfo = uploadBLL.SelectSYS_UPLOAD(id);
            if (uploadinfo != null)
            {
                if (uploadinfo.I_WENJIANLX == 7 || uploadinfo.I_WENJIANLX == 8 || uploadinfo.I_WENJIANLX == 9||
                    uploadinfo.I_WENJIANLX == 10 || uploadinfo.I_WENJIANLX == 11 || uploadinfo.I_WENJIANLX == 12
                    || uploadinfo.I_WENJIANLX == 13)
                {
                    PageTools.AlertMsg(this, "文件为证件类型不可删除，可直接上传新文件");
                    return;
                }
                else
                {
                    uploadBLL.DeleteSYS_UPLOADsDynamic(" ID=" + id);
                    BindUploadGV();
                    PageTools.AlertMsg(this, "删除成功");
                }
            }
        }

        private void SetVisabled()
        {
            if (Request["laihanlc"] != null && Convert.ToInt32(Request["laihanlc"]) > 0)
            {
                gvWenJian.Columns[3].Visible = false;
            }
        }
    
        #endregion
    }
}